package com.hst.web.common.metaviewer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.entity.TDictCatalog;
import com.hst.core.meta.viewer.DefaultMetaViewer;
import com.hst.core.meta.viewer.IMetaViewer;

@Service
@Qualifier("employeeName")
public class EmployeeNameViewer extends DefaultMetaViewer implements IMetaViewer{
	
	ThreadLocal<Map<String, Map<String, String>>> dictDatas = new ThreadLocal<>();
	
	@Autowired
	ISQLDao sql;

	@Autowired
	IORDao dao;
	
	List<String> dictNames;
	
	@Override
	public void setup() {
		if (dictDatas.get() == null)
			dictDatas.set(new HashMap<>());
	}

	@Override
	public void clean() {
		dictDatas.set(null);
	}

	@PostConstruct
	void init() {
		dictNames = new ArrayList<>();
		dao.list(TDictCatalog.class).forEach(dc -> {
			dictNames.add(dc.getId());
		});
	}
	
	synchronized Map<String, String> getDatas(String name) {
 		Map<String, Map<String, String>> _datas = dictDatas.get();
		if (!_datas.containsKey(name)) {
			Map<String, String> datas = new HashMap<>();

			List<?> lists;
			if (dictNames.contains(name)) {
				Map<String, Object> querys = new HashMap<>();
				querys.put("name", name);
				lists = sql.query("dicts.dicts", querys);
			} else {
				lists = sql.query("dicts." + name);
			}

			lists.stream().forEach(m -> {
				if (null == m)
					return;
				if (m instanceof String) {
					datas.put((String) m, (String) m);
				}
				try {
					String id = BeanUtils.getProperty(m, "id");
					String text = BeanUtils.getProperty(m, "text");
					if (null == text)
						text = BeanUtils.getProperty(m, "name");
					datas.put(id, text);
				} catch (Exception ex) {
					throw new RuntimeException(new Error(ex.getMessage()));
				}
			});
			_datas.put(name, datas);
		}

		return _datas.get(name);
	}
	
	@Override
	public String[] convert(String args, Object v, Object row) {
		if (null == v)
			return new String[] {""};
		String k = ConvertUtils.convert(v);
		Map<String, String> datas = getDatas("employee-all");
		if (datas.containsKey(k)) {
			return new String[] {datas.get(k)};
		} else {
			return new String[] {"[" + k + "]"};
		}
	}
}
